import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/utils/shared/shared_storage.dart';
import 'package:flutter_09_game/utils/shared/shared_key.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';

/// 音效管理器
/// 负责游戏音效的播放和控制
class SoundManager {
  static final SoundManager _instance = SoundManager._internal();

  factory SoundManager() => _instance;

  SoundManager._internal();

  late AudioPlayer _audioPlayer;
  bool _isInitialized = false;

  /// 初始化音效管理器
  Future<void> initialize() async {
    if (_isInitialized) return;

    _audioPlayer = AudioPlayer();
    _isInitialized = true;
    clog('SoundManager: 音效管理器初始化完成');
  }

  /// 播放按键音效
  Future<void> playButtonSound() async {
    try {
      // 检查音效开关状态
      bool isSoundEnabled = await getSoundEnabled();
      if (!isSoundEnabled) {
        clog('SoundManager: 音效已关闭，跳过播放');
        return;
      }

      // 确保已初始化
      if (!_isInitialized) {
        await initialize();
      }

      // 播放音效

      // await _audioPlayer.play(AssetSource(Assets.effect));
      await _audioPlayer.play(AssetSource('voice/effect.mp3'));
      clog('SoundManager: 播放按键音效');
    } catch (e) {
      clog('SoundManager: 播放音效失败 - $e');
    }
  }

  /// 获取音效开关状态
  Future<bool> getSoundEnabled() async {
    try {
      bool? enabled = SharedStorage().prefs.getBool(SharedKey.gameSoundEnabled);
      return enabled ?? false; // 默认开启音效
    } catch (e) {
      clog('SoundManager: 获取音效状态失败 - $e');
      return true; // 出错时默认开启
    }
  }

  /// 设置音效开关状态
  Future<void> setSoundEnabled(bool enabled) async {
    try {
      await SharedStorage().prefs.setBool(SharedKey.gameSoundEnabled, enabled);
      clog('SoundManager: 设置音效状态为 $enabled');
    } catch (e) {
      clog('SoundManager: 设置音效状态失败 - $e');
    }
  }

  /// 切换音效开关状态
  Future<bool> toggleSoundEnabled() async {
    bool currentState = await getSoundEnabled();
    bool newState = !currentState;
    await setSoundEnabled(newState);
    return newState;
  }

  /// 释放资源
  Future<void> dispose() async {
    if (_isInitialized) {
      await _audioPlayer.dispose();
      _isInitialized = false;
      clog('SoundManager: 音效管理器已释放');
    }
  }
}
